package com.atguigu.tingshu.search.recevier;


import com.atguigu.tingshu.constant.RabbitConstant;
import com.atguigu.tingshu.search.service.SearchService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;



/**
 * ClassName: SearchReceiver
 * Package: com.atguigu.tingshu.search.recevier
 * Description:监听Elasticsearch消息
 */
@Component
@Slf4j
public class SearchReceiver {
    @Autowired
    private SearchService searchService;

    /**
     * 监听专辑添加
     */
    @SneakyThrows
    @RabbitListener(queues = RabbitConstant.ELASTICSEARCH_ADD_QUEUE)
    public void addAlbumToElasticsearch(Message message, Channel channel){
        //获取消息编号
        long deliveryTag= message.getMessageProperties().getDeliveryTag();
        try {
            //获取消息内容
            long albumId = Long.parseLong(new String(message.getBody()));
            //将专辑添加到Elasticsearch中
            searchService.albumToElasticsearch(albumId);
            //应答
            channel.basicAck(deliveryTag,false);
        } catch (Exception e) {
            e.printStackTrace();
            if (message.getMessageProperties().getRedelivered()){
                //第二次出异常,记录消息,后续处理
                log.error("消息连续两次消费失败,记录消息........");
                channel.basicReject(deliveryTag,false);
            }else {
                //第一次出异常,消息重新投递
                log.info("消息第一次消费失败,重新投递");
                channel.basicReject(deliveryTag,true);
            }
        }

    }

    /**
     * 监听专辑移除
     */
    @SneakyThrows
    @RabbitListener(queues = RabbitConstant.ELASTICSEARCH_REMOVE_QUEUE)
    public void removeAlbumFromElasticsearch(Message message, Channel channel){
        //获取消息编号
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            //获取消息内容
            long albumId = Long.parseLong(new String(message.getBody()));
            //将Elasticsearch中的专辑删除掉
            searchService.removeAlbumFromElasticsearch(albumId);
            //应答
            channel.basicAck(deliveryTag,false);
        } catch (Exception e) {
            e.printStackTrace();
            if (message.getMessageProperties().getRedelivered()){
                //第二次出异常,记录消息,后续处理
                log.error("消息连续两次消费失败,记录消息........");
                channel.basicReject(deliveryTag,false);
            }else {
                //第一次出异常,消息重新投递
                log.info("消息第一次消费失败,重新投递");
                channel.basicReject(deliveryTag,true);
            }
        }

    }


}
